﻿using System;
using System.IO;
using SmartContentModule.Helpers;
using SmartContentModule.VersionManagement;

namespace SmartContentModule
{
    public class ContentControl : System.Web.UI.Control
    {
        /// <summary>
        /// 
        /// </summary>
        public string Src
        {
            get
            {
                return Convert.ToString(ViewState["Src"]);
            }
            set
            {
                ViewState["Src"] = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (!this.Visible || this.Page == null || this.DesignMode) return;

            if (string.IsNullOrEmpty(Src)) return;

            string src = this.Page.ResolveUrl(Src);

            string extension = Path.GetExtension(src);
            if (string.IsNullOrEmpty(extension)) return;

            switch (extension.ToLowerInvariant())
            {
                case ".js":
                    src = GetSourcePathWithModifyDate(src);
                    writer.Write("<script type=\"text/javascript\" src=\"{0}\"></script>", src);
                    break;
                case ".css":
                    bool useDynamicRender = ContentModule.Enabled;
                    if (useDynamicRender)
                    {
                        try
                        {
                            writer.Write(VersionManager.GetHandlerUrlForCss(src));
                        }
                        catch (Exception ex)
                        {
                            //use old style
                            useDynamicRender = false;
                            ExceptionHelper.HandleError(String.Empty, ex);
                        }
                    }

                    if (!useDynamicRender)
                    {
                        src = GetSourcePathWithModifyDate(src);
                        writer.Write("<link type=\"text/css\" rel=\"stylesheet\" href=\"{0}\" />", src);
                    }
                    break;
            }
        }

        private string GetSourcePathWithModifyDate(string src)
        {
            string serverPhysicalPath = this.Page.Server.MapPath(src);

            if (File.Exists(serverPhysicalPath))
            {
                src += "?" + File.GetLastWriteTime(serverPhysicalPath).ToString("yyyyMMddHHmmss");
            }
            return src;
        }
    }

}
